package com.bigwork.controller;

import com.bigwork.dto.user.*;
import com.bigwork.entity.User;
import com.bigwork.exception.ResourceNotFoundException;
import com.bigwork.mapper.UserMapper;
import com.bigwork.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;
    private final UserMapper userMapper; // For convenience to get current user from DB

    @PostMapping("/register")
    public ResponseEntity<UserResponse> registerUser(@Valid @RequestBody UserRegistrationRequest request) {
        log.info("API call to register user with username: {}", request.getUsername());
        UserResponse registeredUser = userService.register(request);
        return new ResponseEntity<>(registeredUser, HttpStatus.CREATED);
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> loginUser(@Valid @RequestBody UserLoginRequest request) {
        log.info("API call to login user: {}", request.getUsername());
        String token = userService.login(request);
        log.info("User {} logged in successfully.", request.getUsername());
        return ResponseEntity.ok(Map.of("token", token));
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')") // Only Admin can get user by ID
    public ResponseEntity<UserResponse> getUserById(@PathVariable Long id) {
        log.info("API call to get user by ID: {}", id);
        UserResponse user = userService.findUserById(id);
        return ResponseEntity.ok(user);
    }

    @GetMapping("/me")
    public ResponseEntity<UserResponse> getCurrentUser(Authentication authentication) {
        log.info("API call to get current user info for: {}", authentication.getName());
        User user = getCurrentAuthenticatedUser(authentication);
        UserResponse userResponse = userService.findUserById(user.getId());
        return ResponseEntity.ok(userResponse);
    }

    @PutMapping("/me")
    public ResponseEntity<UserResponse> updateCurrentUser(@Valid @RequestBody UserUpdateRequest request, Authentication authentication) {
        User currentUser = getCurrentAuthenticatedUser(authentication);
        log.info("API call to update current user ID: {}", currentUser.getId());
        UserResponse updatedUser = userService.updateUser(currentUser.getId(), request);
        return ResponseEntity.ok(updatedUser);
    }

    private User getCurrentAuthenticatedUser(Authentication authentication) {
        String username = authentication.getName();
        User user = userMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("User not found from token");
        }
        return user;
    }
}